package com.keyue.common.utils;


import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 *
 * @author achims
 * @date 2019/11/4
 * 用于转换成json字符串以及解析成对象
 */
@Slf4j
public class JsonUtil {

    private static ObjectMapper mapper = new ObjectMapper();

    static {
        log.info("注册jackson-datatype-jsr310的java8时间处理模块");
        mapper.findAndRegisterModules();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object paramT, JsonGenerator paramJsonGenerator,
                                  SerializerProvider paramSerializerProvider) throws IOException {
                //设置返回null转为 空字符串""
                paramJsonGenerator.writeString("");
            }
        });
    }




    /**
     * Create empty json node
     *
     * @return
     */
    public static ObjectNode createJsonNode() {
        return mapper.createObjectNode();
    }

    /**
     * Create empty json Array
     *
     * @return
     */
    public static ArrayNode createJsonArray() {
        return mapper.createArrayNode();

    }

    /**
     * Convert the object to corresponding json string
     *
     * @param obj
     * @return
     */
    public static String toJsonString(Object obj) {
        try {
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    /**
     * 转成格式化后的json，便于调试排错
     * @param obj
     * @return
     */
    public static String toJsonStringWithDefaultPretty(Object obj) {
        try {
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (JsonProcessingException e) {

            return null;
        }
    }

    public static <T> T jsonToEntity(String json, Class<T> clazz) {
        if (StringUtils.isEmpty(json)) return null;
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 借助json做中转，实体类转实体类
     * @param obj 实体
     * @param clazz 目标类型
     * @param <T> 目标泛型
     * @return 结果
     */
    public static <T> T entityConvert(Object obj, Class<T> clazz) {
        return jsonToEntity(toJsonString(obj), clazz);
    }

    /**
     * 带泛型返回不告警
     * @param json json字符
     * @param typeReference TypeReference
     * @param <R> 返回类型
     * @param <T> 转换的类型
     * @return 转换结果
     * @author 刘迪榕
     * @version Date 2022-08-26
     */
    public static <R, T extends R> R jsonToEntity(String json, TypeReference<T> typeReference) {
        if (StringUtils.isEmpty(json)) return null;
        try {
            return mapper.readValue(json, typeReference);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JsonNode readStringAsJsonNode(String json) {
        try {
            return mapper.readValue(json, JsonNode.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JsonNode valueToTree(Object value) {
        return mapper.valueToTree(value);
    }

    public static  <T> T  treeToValue(JsonNode jsonNode, Class<T> clazz) {
        try {
            return mapper.treeToValue(jsonNode, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 是否爲json格式的數據
     *
     * @param test
     * @return
     */
    public final static boolean isJSONValid(String test) {
        try {
            JSONObject.parseObject(test);
        } catch (JSONException ex) {
            try {
                JSONObject.parseArray(test);
            } catch (JSONException ex1) {
                return false;
            }
        }
        return true;
    }

    public <T> T paraseJsonTOClass(String json, Class<T> cla) {
        try {
            return JSONObject.parseObject(json, cla);
        } catch (JSONException ex) {
            return null;
        }
    }
}
